﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace AcfunUpload
{
    public static class Video
    {
        /// <summary>
        /// 复制源视频文件到临时目录（ffmpeg不支持中文）
        /// </summary>
        /// <param name="p">路径</param>
        /// <returns></returns>
        public static string copyFile(string p)
        {
            string path = p;
            string randName = "boomfun_" + Utils.getTimestamp();
            FileInfo ff = new FileInfo(path);
            File.Copy(p, AppDomain.CurrentDomain.BaseDirectory + "/temp/" + randName + ff.Extension, true);
            path = AppDomain.CurrentDomain.BaseDirectory + "/temp/" + randName + ff.Extension;
            return path;
        }
        /// <summary>
        /// 获取视频长度
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static VideoTime getVideoTime(string p)
        {
            string path = p;
            VideoTime vt = null;
            using (Process pro = new Process())
            {
                pro.StartInfo.UseShellExecute = false;
                pro.StartInfo.ErrorDialog = false;
               // pro.StartInfo.StandardOutputEncoding = Encoding.UTF8;
                pro.StartInfo.RedirectStandardError = true;

                pro.StartInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + "ffmpeg.exe";
                pro.StartInfo.Arguments = " -i " + path;

                pro.Start();
                StreamReader errorreader = pro.StandardError;
                pro.WaitForExit(1000);

                string result = errorreader.ReadToEnd();
                if (!string.IsNullOrEmpty(result))
                {
                    string rex = @"Duration: (\d+):(\d+):(\d+).(\d+)";
                    Match match = Regex.Match(result, rex);
                    int ms = Convert.ToInt32(match.Groups[4].Value);
                    int s = Convert.ToInt32(match.Groups[3].Value);
                    int m = Convert.ToInt32(match.Groups[2].Value);
                    int h = Convert.ToInt32(match.Groups[1].Value);
                    vt = new VideoTime(ms, s, m, h, h + ":" + m + ":" + s + "." + ms);
                }
                
            }
            return vt;
        }
        /// <summary>
        /// 分割视频
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="v">视频时间</param>
        /// <returns></returns>
        public static List<UploadInfo> dividedVideo(string path,VideoTime v,int _t)
        {
            string result = "";
            string startTime = v.startTime;
            
            string dividedPath = AppDomain.CurrentDomain.BaseDirectory + "temp/";
            int time = _t;
            int pathCount = (int)Math.Ceiling((v.minute + v.hour * 60.00) / time);
            DataSaving.pgb.Value = 0;
            DataSaving.pgb.Maximum = pathCount;

            string endTime = "00:" + Math.Abs((v.minute + v.hour * 60.00) - (int)Math.Floor((v.minute + v.hour * 60.00) / time) * time) + ":"+v.second;
            Utils.console(0, pathCount + "");
            FileInfo fi = new FileInfo(path);
            List<UploadInfo> us = new List<UploadInfo>();
           
            for (int i = 1; i <= pathCount; i++)
            {
                DataSaving.pgb.Value = i;
                DataSaving.d.changeStatus("分割第" + i + "段视频");
                int minute = i * time;
                int hour = (int)Math.Floor((double)minute / 60);
                minute = minute - hour * 60;
                string st = startTime;
                string et = (i == pathCount) ? endTime : hour + ":"+ minute + ":00";
                string subPath = dividedPath + fi.Name.Replace(fi.Extension,"") + "_" + i + fi.Extension;
                Utils.console(0, et + "");
                using (Process pro = new Process())
                {
                    pro.StartInfo.UseShellExecute = false;
                    pro.StartInfo.ErrorDialog = false;
                    pro.StartInfo.RedirectStandardError = true;
                    pro.StartInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + "ffmpeg.exe";
                    pro.StartInfo.Arguments = "-ss "+ st + " -t "+((i==pathCount)? endTime : "00:"+ time + ":00") + " -i "+path+" -vcodec copy -acodec copy "+ subPath;
                    Utils.console(0, pro.StartInfo.Arguments);
                    pro.StartInfo.CreateNoWindow = false;//不创建进程窗口
                    pro.Start();
                    StreamReader errorreader = pro.StandardError;
                    pro.WaitForExit(1000);
                    result = errorreader.ReadToEnd();
                    Utils.console(1, result);
                    
                   
                }
                startTime = et;
                FileInfo fis = new FileInfo(subPath);
                us.Add(new UploadInfo(fis.FullName, fis.Length + ""));

            }
            DataSaving.d.changeStatus("任务完成，文件名前缀为" + fi.Name.Replace(fi.Extension, ""));
            File.Delete(path);
            ProcessStartInfo psi = new ProcessStartInfo("Explorer.exe");
            psi.Arguments = "/e," + AppDomain.CurrentDomain.BaseDirectory + "temp";
            Process.Start(psi);
            
            return us;
        }
    }
}
